package models

import (
	"fmt"
	"github.com/go-redis/redis"
	"log"
	"newGame/utils"
)

type Data uint

func init(){
	var err error
	if err = initMap();err != nil{
		log.Fatal("初始化数据失败:",err)
	}
	if err = initMonster();err != nil{
		log.Fatal("初始化数据失败:",err)
	}
	if err = initNpc();err != nil{
		log.Fatal("初始化数据失败:",err)
	}
}
func normalInit(path, desc string) error {
	var (
		value,
		data interface{}
		realData []interface{}
		jsonData map[string]interface{}
		err      error
		text     []byte
		pipe     redis.Pipeliner
		key,
		typeName string
	)
	if text, err = utils.ReadAllFromFile(path, desc); err != nil {
		return err
	}
	if jsonData,err = utils.UnMarshal(text); err != nil {
		return err
	}
	realData = jsonData["unmarshalData"].([]interface{})
	if Db.RedisDb == nil {
		return fmt.Errorf("RedisDb未初始化")
	}
	pipe = Db.RedisDb.Pipeline()
	switch desc {
	case "map":
		for _,data = range realData{
			for key,value = range data.(map[string]interface{}){
				typeName = key
				utils.ScanMapToDb(value.(map[string]interface{}), nil, pipe,typeName)
			}
		}
	case "npc":
		for _,data = range realData{
			for key,value = range data.(map[string]interface{}){
				typeName = key
				utils.ScanNpcToDb(value.([]interface{}), pipe,typeName,Db.RedisDb)
			}
		}
	case "monster":
		for _,data = range realData{
			for key,value = range data.(map[string]interface{}){
				typeName = key
				utils.ScanMonsterToDb(value.([]interface{}), pipe,typeName,Db.RedisDb)
			}
		}
	}
	if _, err = pipe.Exec();err != nil{
		log.Fatal(err)
	}
	return nil
}
func initMap() error {
	return normalInit("./datas/map.json", "map")
}
func initNpc() error {
	return normalInit("./datas/npc.json", "npc")
}
func initMonster() error {
	return normalInit("./datas/monster.json", "monster")
}
